/**
 * Copyright 2012-2013 Brin.com
 * All rights reserved.
 * 
 * @project
 * @author Brin
 * @version 1.0
 * @data 2013-03-10
 */
package com.brin.core.util;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;

import com.brin.core.common.AjaxJsonValueProcessorImpl;
import com.brin.core.common.JsonValueProcessorImpl;
import com.brin.core.zui.dataobject.IJSONObject;

public class JSONUtil {

	public static JsonConfig DEFAULT_JSON_CONFIG = null;
	public static JsonConfig AJAX_JSON_CONFIG = null;
	
	static {
		
        AJAX_JSON_CONFIG =  new JsonConfig();
        AJAX_JSON_CONFIG.registerJsonValueProcessor(java.util.Date.class, new AjaxJsonValueProcessorImpl());
        AJAX_JSON_CONFIG.registerJsonValueProcessor(String.class, new AjaxJsonValueProcessorImpl());
        DEFAULT_JSON_CONFIG =  new JsonConfig();
        DEFAULT_JSON_CONFIG.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessorImpl());
    }
	
	/**
	 * 对JSON每一个KEY的VALUE文本中可能引起问题的特殊字符串做JS转义 双引号,单引号都转义
	 * @param json
	 * @return
	 */
	public static String escapeValue(String json) {
		if (StringUtil.isBlank(json)) return json;
		
		json = json.replaceAll("\\\\", "\\\\\\\\");
        json = json.replaceAll("\"", "\\\\\"");
        json = json.replaceAll("'", "\\\\'");
        json = json.replaceAll("\b", "\\\\b");
        json = json.replaceAll("\n", "\\\\n");
        json = json.replaceAll("\t", "\\\\t");
        json = json.replaceAll("\f", "\\\\f");
        json = json.replaceAll("\r", "\\\\r");
        
        return json;
	}
	
	/**
	 * 将一组key,value数据转换为JSON格式。注意：VALUE中的特殊字符串已做了JS转义。 例如： 输入："name","flouny"
	 * 输出："name:flouny"
	 * @param key
	 * @param value
	 * @return
	 */
	public static String toKeyValue(String key, String value) {
		 if (StringUtil.isEmpty(key))  throw new RuntimeException("The key of json-string not exist!");
		 
		 return (value == null)?key.concat(":null") : key.concat(":\"").concat(escapeValue(value)).concat( "\"");
	 }
	
	/**
     * Flash中使用的字符转译
     * 
     * @param str
     * @return
     */
    public static String flashEscapeValue(String json) {
        if (json == null || json.length() <= 0)
            return json;

        json = json.replaceAll("<", "＜");
        json = json.replaceAll(">", "＞");
        json = json.replaceAll("\\\\", "\\\\\\\\");
        json = json.replaceAll("\"", "\\\\\"");
        json = json.replaceAll("'", "\\\\'");
        json = json.replaceAll("\b", "\\\\b");
        json = json.replaceAll("\n", "\\\\n");
        json = json.replaceAll("\t", "\\\\t");
        json = json.replaceAll("\f", "\\\\f");
        json = json.replaceAll("\r", "\\\\r");

        return json;
    }
	 
	 /**
	  * 将JSON转为JavaBean
	  * @param obj
	  * @param clazz
	  * @return
	  */
	 public static Object toBean(Object obj, Class<?> clazz) {
		 if (obj instanceof JSONObject) {
			 
			 return JSONObject.toBean((JSONObject) obj, clazz);
		 } else if (obj instanceof String) {
			 
			 return JSONObject.toBean(JSONObject.fromObject(obj), clazz);
		 }
		 
		 return null;
	 }
	 
	 /**
	  * 将bean转换为jsonString ,支持标准javabean,Collection,Object[]
	  * 如果需要结果给javacript 使用 需要使用toJSONString(object,JSONUtil.AJAX_JSON_CONFIG);
	  * @param obj
	  * @return
	  */
	 public static String toJSONString(Object obj) {
		 
		 return toJSONString(obj,DEFAULT_JSON_CONFIG);
	 }
	 
	 /**
	  * 将bean 转换为jsonString,需要指定参数JsonConfig
	  * @param obj
	  * @param jsonConfig
	  * @return
	  */
	 @SuppressWarnings({ "static-access", "unchecked" })
	public static String toJSONString(Object obj,  JsonConfig  jsonConfig ) {
		 if(obj == null) return null;
	 
		 String result = null;
	 
		 if(obj instanceof String) {
		 
			 return (String)obj;
		 } else if (obj instanceof Collection) {
			 JSONArray jsons = new JSONArray();
			 jsons.addAll((Collection<?>) obj,jsonConfig);
			 result = jsons.toString();
		 } else if(JSONUtils.isArray(obj)) {
			 JSONArray jsons = new JSONArray();
			 jsons.add(obj,jsonConfig);
			 result = jsons.toString();
		 } else if(obj instanceof Map) {
			 JSONObject json = new JSONObject();
			 json.accumulateAll((Map<?, ?>)obj, jsonConfig);
			 result = json.toString();
		 } else {
			 JSONObject json = new JSONObject();
			 result = json.fromObject(obj,jsonConfig).toString();
		 }
        
		 if(AJAX_JSON_CONFIG.equals(jsonConfig)) {
			 result = result.replaceAll("\\\\\\\\","\\\\");
			 result = result.replaceAll("\\\\\"","\"");
			 result = result.replaceAll("\\\\\'","\'");
		 }
      
		 return result;
	}
	    
    /**
     * 将json 对象转为javabean
     * @param json
     * @param beanClass
     * @return
     */
	public static Object jsonObjectToBean(JSONObject json, Class<?> beanClass) {
		
		return JSONObject.toBean(json,beanClass);
    }
		
	/**
	 * 将json String 对象转为javabean
	 * @param jsonString
	 * @param beanClass
	 * @return
	 */
	public static Object jsonStringObjectToBean(String jsonString,Class<?> beanClass){
        
        return JSONObject.toBean(JSONObject.fromObject(jsonString),beanClass);
    }
	
	/**
	 * 
	 * @param list
	 * @return
	 */
    public static String toJSONString(List<?> list) {
    	if (list == null || list.isEmpty()) return "[]";
    	
    	StringBuffer sb = new StringBuffer("[");
    	for (int i = 0; i < list.size(); i++) {
    		IJSONObject obj = (IJSONObject)list.get(i);
    		if (i == 0) {
    			sb.append(obj.toJSONString());
    		} else {
    			sb.append("," + obj.toJSONString());
    		}
    	}
	 
    	sb.append("]");
	 
    	return sb.toString();
    }
}
